package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    //
    private Mapper mapper;

    //改造构造函数，把mapper类传入
    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }
    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            System.out.println(request.getUrl());
            String hostName = request.getHost().split(":")[0];
            String url = request.getUrl();
            Host host = mapper.getHostMap().get(hostName);


            //先判度是否能通过url找到host
            if(host != null){
                host.getContextMap().forEach((key,value)->{
                    //再判断能否找到context
                    if(url.startsWith("/"+key)){
                        Wrapper wrapper = value.getWrapperMap().get(url.replace("/" + key, ""));
                        //在判断能否找到wrapper
                        if(wrapper != null){
                            try {
                                //找到wrapper后调用wrapper中的servlet
                                wrapper.getServlet().service(request,response);
                                return;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
                //如果上述条件有一个未找到，则调用静态资源
            }else{
                response.outputHtml(request.getUrl());
            }


            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
